package com.smart.car.record.init;

import com.alibaba.fastjson.JSONObject;
import com.smart.car.common.res.constant.Constants;
import com.smart.car.record.entity.RecordChargeRule;
import com.smart.car.record.service.RecordChargeRuleService;
import com.smart.car.record.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 初始化计费规则到cache中
 * 项目启动时就加载缓存，待数据变更后再回刷缓存。
 *
 * @author: zoutao
 * @date: 2021-05-06-11:24
 */
@Component
@Order(value = 1)
public class StartUpApplicationRunner implements ApplicationRunner {

    @Autowired
    private RedisService redisService;

    @Autowired
    private RecordChargeRuleService chargeRuleService;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        //查询db中的计费规则
        List<RecordChargeRule> rules = chargeRuleService.list();
        //redis中是否已存在？
        if (!redisService.exist(Constants.cache.CHARGINGRULE)) {
            redisService.cacheObject(Constants.cache.CHARGINGRULE, JSONObject.toJSONString(rules));
        }
    }
}
